<?php

namespace App\Http\Controllers\V1;

use App\Http\Controllers\ApiBaseController;
use App\Http\Requests\CustomerRequest;
use App\Http\Requests\SysUserRequest;
use App\Models\BalanceLog;
use App\Models\CzOrder;
use App\Models\SysRole;
use App\Models\SysUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class CustomerController extends ApiBaseController
{
    public function index(Request $request)
    {
        $paginator = SysUser::with('group')->filter($request->all())
            ->where('user_type', $this->customer_config_map['customer_type'])
            ->paginate($this->pageSize);
        $list = $paginator->items();
        foreach ($list as $key => &$value) {
            // var_dump($value['id']);
            // 累计充值中
            $all_ing_user_money = CzOrder::where('create_by', $value['id'])->where('pay_status', 1)->whereIn('order_status', [1, 2, 5, 6])->sum('price');
            $balance = $value['balance'];
            $real_money = number_format($all_ing_user_money + $balance, 2);
            $value['real_money'] = $real_money;
        }
        return success([
            'rows' => $paginator->items(),
            'total' => $paginator->total(), // 获取结果集中的数据总数
            'last_page' => $paginator->lastPage(),
            'currentPage' => $paginator->currentPage()
        ]);
    }

    public function listAll(Request $request)
    {
        $items = SysUser::where('user_type', $this->customer_config_map['customer_type'])->get();
        return success(['data' => $items]);
    }
    public function userExport(Request $request)
    {

        set_time_limit(600);
        $params  = $request->all();

        // $params['order'] = $params['order'] ?? "desc";
        $fileName = "客户导出[" . date('YmdHi') . "].csv";
        // 清空输出流，防止有别的信息
        ob_end_clean();
        // 打开一个输出流
        ob_start();
        // 设置header信息
        header("Content-Type: text/csv");
        header("Content-Disposition:filename=" . $fileName);
        header("Access-Control-Allow-Origin: *");

        // 打开文件流
        $fileHandle = fopen('php://output', 'w');
        //转码 防止乱码
        fwrite($fileHandle, chr(0xEF) . chr(0xBB) . chr(0xBF));
        $header_data = [
            '用户名称', '用户昵称', '用户分组', "状态", '余额', '授信', '实际欠款', '创建时间', '修改时间',
        ];
        if (!empty($header_data)) {
            fputcsv($fileHandle, $header_data);
        }
        // 先把标题写进去
        //        fputcsv($fileHandle, $title);
        if (isset($request['ids'])) {
            // 导出部分
            SysUser::where('user_type', $this->customer_config_map['customer_type'])->whereIn('id', $request['ids'])->dataFilter()->with(['group'])->orderBy("id", 'desc')
                ->chunk(10000, function ($items) use ($fileHandle) {
                    $arrs = $items->toArray();
                    foreach ($arrs as $item) {
                        // 累计充值中
                        $all_ing_user_money = CzOrder::where('create_by', $item['id'])->whereIn('order_status', [1, 2, 5, 6])->sum('price');
                        $balance = $item['balance'];
                        // 实际欠款
                        $money = number_format($balance + $all_ing_user_money, 2);
                        $tmp_data = [
                            $item['username'],
                            $item['nickname'],
                            $item['group'] ? $item['group']["group_name"] : "无",
                            $item['status'] == 1 ? "启用" : '禁用',
                            $item['balance'],
                            $item['credit'],
                            $money, //todo实际欠款
                            $item['created_at'],
                            $item['updated_at'],
                        ];
                        fputcsv($fileHandle, $tmp_data);
                    }
                    //每2000条释放一次资源
                    ob_flush();
                    flush();
                });
        } else {
            SysUser::where('user_type', $this->customer_config_map['customer_type'])->filter($params)->dataFilter()->with(['group'])->orderBy("id", "desc")
                ->chunk(10000, function ($items) use ($fileHandle) {
                    $arrs = $items->toArray();
                    foreach ($arrs as $item) {
                        // 累计充值中
                        $all_ing_user_money = CzOrder::where('create_by', $item['id'])->whereIn('order_status', [1, 2, 5, 6])->sum('price');
                        $balance = $item['balance'];
                        // 实际欠款
                        $money = number_format($balance + $all_ing_user_money, 2);
                        $tmp_data = [
                            $item['username'],
                            $item['nickname'],
                            $item['group'] ? $item['group']["group_name"] : "无",
                            $item['status'] == 1 ? "启用" : '禁用',
                            $item['balance'],
                            $item['credit'],
                            $money,  //todo实际欠款
                            $item['created_at'],
                            $item['updated_at'],
                        ];
                        fputcsv($fileHandle, $tmp_data);
                    }
                    //每2000条释放一次资源
                    ob_flush();
                    flush();
                });
        }
        //释放资源
        ob_flush();
        flush();
        ob_end_clean();
    }

    public function show(Request $request, SysUser $model)
    {
        $id = $request->get('id', 0);
        $data = $model->where('user_type', $this->customer_config_map['customer_type'])->find($id);
        //        $roles = SysRole::all();
        //        $user_roleids = DB::table('sys_user_role')->where('user_id', $id)->pluck('role_id');
        return success([
            'data' => $data,
            //            'roles' => $roles,
            //            'roleIds' => $user_roleids
        ]);
    }

    public function create(CustomerRequest $request)
    {
        //        $params = $request->all();
        $params = $request->except(['balance', 'credit', 'api_secret', 'user_type']);


        DB::transaction(function () use ($params) {
            $params['user_type'] = $this->customer_config_map['customer_type'];
            $params['roleIds'] = $this->customer_config_map['role_id'];
            $params['dept_id'] = $this->customer_config_map['dept_id'];

            $user = SysUser::create($params);
            $user_id = $user->id;
            $roleIds = $params['roleIds'];
            if (count($roleIds) > 0) {
                foreach ($roleIds as $role_id) {
                    $add_datas[] = [
                        'user_id' => $user_id,
                        'role_id' => $role_id,
                    ];
                }
                DB::table('sys_user_role')->where('user_id', $user_id)->delete();
                DB::table('sys_user_role')->insertOrIgnore($add_datas);
            } else {
                DB::table('sys_user_role')->where('user_id', $user_id)->delete();
            }
        });
        return success([], '更新成功');
    }

    public function update(CustomerRequest $request, SysUser $model)
    {
        //        $params = $request->except(['password','login_ip','login_time','create_by']);
        $params = $request->except(['password', 'login_ip', 'login_time', 'create_by', 'balance', 'credit', 'api_secret', 'user_type']);
        // return $params;
        $id = $request->post('id');
        $user = $model->where('user_type', $this->customer_config_map['customer_type'])->find($id);
        if (!$user) {
            return error('数据不存在');
        }
        DB::transaction(function () use ($params, $user) {
            $user->update($params);
            /*
            $user_id = $user->id;
            $roleIds = $params['roleIds'];
            if(count($roleIds) > 0){
                foreach ($roleIds as $role_id){
                    $add_datas[] = [
                        'user_id' => $user_id,
                        'role_id' => $role_id,
                    ];
                }
                DB::table('sys_user_role')->where('user_id',$user_id)->delete();
                DB::table('sys_user_role')->insertOrIgnore($add_datas);
            }else{
                DB::table('sys_user_role')->where('user_id',$user_id)->delete();
            }
            */
        });
        return success([], '更新成功');
    }
    //todo
    public function destroy($ids, Request $request, SysUser $model)
    {
        $id_arr = explode(',', $ids);
        $model->destroy($id_arr);
        return success([], '删除成功');
    }

    public function changeStatus(Request $request, SysUser $model)
    {
        $params = $request->all();
        $id = $request->post('user_id');
        $status = $request->post('status');

        $user = $model->where('user_type', $this->customer_config_map['customer_type'])->find($id);
        if (!$model) {
            return error('数据不存在');
        }
        $user->update([
            'status' => $status
        ]);
        return success([], '更新成功');
    }
    public function resetPwd(Request $request, SysUser $model)
    {
        $params = $request->all();
        $id = $request->post('user_id');
        $password = $request->post('password');

        $user = $model->where('user_type', $this->customer_config_map['customer_type'])->find($id);
        if (!$model) {
            return error('数据不存在');
        }
        /*
        $user->update([
            'password' => Hash::make($password)
        ]);
        */
        $user->password = trim($password);
        $user->save();
        return success([], '更新成功');
    }

    public function changePwd(Request $request)
    {
        $user = auth()->user();
        if (Hash::check($request->post('old_password'), $user->password) == false) {
            return error('旧密码不匹配');
        }
        //        $user->password = Hash::make(trim($request->post('new_password')));
        $user->password = trim($request->post('new_password'));
        $user->save();
        return success([], '修改成功');
    }

    public function recharge(CustomerRequest $request, SysUser $model)
    {
        $params = $request->all();
        $id = $request->post('id');
        $user = $model->where('user_type', $this->customer_config_map['customer_type'])->find($id);
        if (!$user) {
            return error('数据不存在');
        }
        DB::transaction(function () use ($params, $user) {
            $money = floatval($params['money']);
            BalanceLog::create([
                'order_sn' => 'HT' . date("YmdHis") . $user->id . rand(1000, 9999) . rand(1000, 9999),
                'money' => $money,
                'bf_balance' => $user->balance,
                'af_balance' => $user->balance + $money,
                'bank' => $params['bank'],
                'type' => $money > 0 ? 1 : 2,
                'remark' => $params['remark2'] ?? '管理员' . ($money > 0 ? '加款' : '扣款') . abs($money),
                'user_id' => $user->id,
            ]);
            $user->increment('balance', floatval($params['money']));
        });
        return success([], '更新成功');
    }
    public function credit(CustomerRequest $request, SysUser $model)
    {
        $params = $request->all();
        $id = $request->post('id');
        $user = $model->where('user_type', $this->customer_config_map['customer_type'])->find($id);
        if (!$user) {
            return error('数据不存在');
        }
        $user->credit = floatval($params['money']);
        $user->save();
        return success([], '更新成功');
    }
    public function resetKey(Request $request, SysUser $model)
    {
        $id = $request->post('user_id');
        $user = $model->where('user_type', $this->customer_config_map['customer_type'])->find($id);
        if (!$model) {
            return error('数据不存在');
        }
        $user->api_secret = md5(uniqid() . rand(1000, 9999));;
        $user->save();
        return success([], '更新api密钥成功');
    }
    public function getStatics(Request $request)
    {
        $id = request('id');
        if (!$id) {
            return error('参数错误');
        }
        $info = SysUser::find($id);
        if (!$info) {
            return error('商户异常');
        }
        // 累计加款

        $all_add_money = BalanceLog::where('type', 1)->where('user_id', $id)->sum('money');
        // 累计扣款
        $all_del_money = BalanceLog::where('type', 2)->where('user_id', $id)->sum('money');

        // 累计完成充值
        $all_success_user_money = CzOrder::where('create_by', $id)->where('order_status', 3)->sum('price');
        // 累计充值中
        $all_ing_user_money = CzOrder::where('create_by', $id)->whereIn('order_status', [1, 2, 5, 6])->sum('price');

        // 累计成本
        $all_success_const_money = CzOrder::where('create_by', $id)->where('order_status', 3)->sum('cost');

        return success([
            "data" => [


                "all_add_money" => $all_add_money,
                "all_del_money" => abs($all_del_money),
                "all_success_user_money" => $all_success_user_money,
                "all_success_const_money" => $all_success_const_money,
                "all_ing_user_money" => $all_ing_user_money,
                "balance" => $info->balance,
                "username" => $info->username,
            ]
        ]);
    }
}
